package com.weixin.paleituo.fragment;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.weixin.paleituo.R;
import com.weixin.paleituo.adapter.StoreHomeAdapter;
import com.weixin.paleituo.application.BaseApplication;
import com.weixin.paleituo.base.BaseFragment;
import com.weixin.paleituo.bean.HotStoreGoods;
import com.weixin.paleituo.bean.StatusCode;
import com.weixin.paleituo.contans.Contans;
import com.weixin.paleituo.http.HttpUtil;
import com.weixin.paleituo.http.ProgressSubscriber;
import com.weixin.paleituo.http.RxHelper;
import com.weixin.paleituo.rxjava.ApiUtils;
import com.weixin.paleituo.util.LoadingDialogUtils;
import com.weixin.paleituo.util.ToastUtils;
import com.weixin.paleituo.util.UIUtils;
import com.weixin.paleituo.view.LoadingPagerHead;
import com.weixin.paleituo.view.YRecycleview;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Author yichao
 * Time  2018/4/4 13:32
 * Dest  店铺所有商品
 */

public class StoreAllGoodsFragment extends BaseFragment {
    @BindView(R.id.tv_recommand_store_goods_all)
    TextView mTvRecommandStoreGoodsAll;
    @BindView(R.id.tv_salenumber_store_goods_all)
    TextView mTvSalenumberStoreGoodsAll;
    @BindView(R.id.tv_price_store_goods_all)
    TextView mTvPriceStoreGoodsAll;
    @BindView(R.id.iv_price_store_goods_all)
    ImageView mIvPriceStoreGoodsAll;
    @BindView(R.id.ll_pricatroot_store_goods_all)
    LinearLayout mLlPricatrootStoreGoodsAll;
    @BindView(R.id.yrecycleview_store_goods_all)
    YRecycleview mYrecycleviewStoreGoodsAll;
    private int priceSore;
    private LoadingPagerHead mLoadingPagerHead;
    private int mStoreId;
    private List<HotStoreGoods> mHotStoreGoods=new ArrayList<>();
    private StoreHomeAdapter mStoreHomeAdapter;
    private Dialog mLoadingDialog;
    private int currentPage=1;

    @Override
    public View initView(final Context context) {

        mLoadingPagerHead = new LoadingPagerHead(context) {
            @Override
            protected void close() {

            }

            @Override
            protected View createSuccessView() {
                return UIUtils.inflate(mContext, R.layout.store_goods_all);
            }

            @Override
            protected void reLoading() {
retry();
            }
        };




        return mLoadingPagerHead;
    }

    /**
     * 重试
     */
    private void retry() {
        Observable<StatusCode<List<HotStoreGoods>>> storeAllGoodsObservable = ApiUtils.getApi().getStoreAllGoods(Contans.defaultToken, "g.goods_salenum", null, null, mStoreId, 1, Contans.rows, BaseApplication.getNewUserId());
        HttpUtil.getInstance().toSubscribe(storeAllGoodsObservable, new ProgressSubscriber<List<HotStoreGoods>>(mContext) {

            @Override
            protected void _onNext(StatusCode<List<HotStoreGoods>> listStatusCode) {
                List<HotStoreGoods> data = listStatusCode.getData();
                if (data!=null &&data.size()>0){
                    mLoadingPagerHead.showPagerView(Contans.STATE_SUCCEED);
                    mHotStoreGoods.clear();
                    mHotStoreGoods.addAll(data);
                    mStoreHomeAdapter.notifyDataSetChanged();
                }else {
                    mLoadingPagerHead.showPagerView(Contans.STATE_EMPTY);

                }
            }

            @Override
            protected void _onError(String message) {
                mLoadingPagerHead.showPagerView(Contans.STATE_ERROR);
                ToastUtils.makeText(message);

            }
        },"",lifecycleSubject,false,true);
    }

    @Override
    protected void initData() {
        super.initData();
        Bundle arguments = getArguments();
        mStoreId = arguments.getInt(Contans.INTENT_EXTRA);

        mHotStoreGoods.clear();
        mStoreHomeAdapter = new StoreHomeAdapter(mContext,mHotStoreGoods);
        mYrecycleviewStoreGoodsAll.setLayoutManager(new LinearLayoutManager(mContext));
        mYrecycleviewStoreGoodsAll.setItemAnimator(new DefaultItemAnimator());
        mYrecycleviewStoreGoodsAll.setAdapter(mStoreHomeAdapter);
        retry();
        mYrecycleviewStoreGoodsAll.setRefreshAndLoadMoreListener(new YRecycleview.OnRefreshAndLoadMoreListener() {
            @Override
            public void onRefresh() {
                Observable observable = ApiUtils.getApi().getStoreAllGoods(Contans.defaultToken, hotSell, recommend, price, mStoreId, 1, Contans.rows,BaseApplication.getNewUserId());
                HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<List<HotStoreGoods>>(mContext) {
                    @Override
                    protected void _onNext(StatusCode<List<HotStoreGoods>> listStatusCode) {
                        mYrecycleviewStoreGoodsAll.setReFreshComplete();

                        List<HotStoreGoods> hotStoreGoods = listStatusCode.getData();

                        if (hotStoreGoods!=null&& hotStoreGoods.size()>0){
                            currentPage=1;
                            mHotStoreGoods.clear();
                            mHotStoreGoods.addAll(hotStoreGoods);

                        }else {
                            ToastUtils.makeText(listStatusCode.getDetailMsg());
                        }
                        mStoreHomeAdapter.notifyDataSetChanged();
                    }

                    @Override
                    protected void _onError(String message) {

                        mYrecycleviewStoreGoodsAll.setReFreshComplete();
                     ToastUtils.makeText(message);


                    }
                },"",lifecycleSubject,false,true);





            }

            @Override
            public void onLoadMore() {

                Observable observable = ApiUtils.getApi().getStoreAllGoods(Contans.defaultToken, hotSell, recommend, price, mStoreId, currentPage+1, Contans.rows,BaseApplication.getNewUserId());


                HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<List<HotStoreGoods>>(mContext) {
                    @Override
                    protected void _onNext(StatusCode<List<HotStoreGoods>> listStatusCode) {
                        mYrecycleviewStoreGoodsAll.setloadMoreComplete();

                        List<HotStoreGoods> hotStoreGoods = listStatusCode.getData();

                        if (hotStoreGoods!=null&& hotStoreGoods.size()>0){
                            currentPage+=1;

                            mHotStoreGoods.addAll(hotStoreGoods);

                        }else {
                            ToastUtils.makeText("没有更多商品了");
                        }
                        mStoreHomeAdapter.notifyDataSetChanged();


                    }

                    @Override
                    protected void _onError(String message) {

                        mYrecycleviewStoreGoodsAll.setloadMoreComplete();
                        ToastUtils.makeText(message);


                    }
                },"",lifecycleSubject,false,true);







            }
        });


    }


/*    /**token	是	String	scmsw
     page	是	int	当前页
     rows	是		每页显示条数
     hotsell	可选	String	g.goods_salenum（销量排序）
     recommend	可选	String	g.recommend_sequence（推荐排序）
     price	可选	Long	价格排序（1-降序，2-升序）
     storeId	是	Long 	店铺id

     */

private  String hotSell;
private String recommend;
private String price;

    @OnClick(R.id.tv_recommand_store_goods_all)
    public void onMTvRecommandStoreGoodsAllClicked() {
        mTvRecommandStoreGoodsAll.setTextColor(UIUtils.getColor(R.color.c_29CE7E));
        mTvSalenumberStoreGoodsAll.setTextColor(UIUtils.getColor(R.color.c_383838));
        mTvPriceStoreGoodsAll.setTextColor(UIUtils.getColor(R.color.c_383838));
        mIvPriceStoreGoodsAll.setImageResource(R.mipmap.direction_default);
        recommend="g.recommend_sequence";

        hotSell=null;
        price=null;
        currentPage=1;


        onClickQuestIntent();

    }

    @OnClick(R.id.tv_salenumber_store_goods_all)
    public void onMTvSalenumberStoreGoodsAllClicked() {
        mTvRecommandStoreGoodsAll.setTextColor(UIUtils.getColor(R.color.c_383838));
        mTvSalenumberStoreGoodsAll.setTextColor(UIUtils.getColor(R.color.c_29CE7E));
        mTvPriceStoreGoodsAll.setTextColor(UIUtils.getColor(R.color.c_383838));
        mIvPriceStoreGoodsAll.setImageResource(R.mipmap.direction_default);
        recommend=null;

        hotSell="g.goods_salenum";
        price=null;
        currentPage=1;
        onClickQuestIntent();
    }

    @OnClick(R.id.ll_pricatroot_store_goods_all)
    public void onMLlPricatrootStoreGoodsAllClicked() {

        mTvRecommandStoreGoodsAll.setTextColor(UIUtils.getColor(R.color.c_383838));
        mTvSalenumberStoreGoodsAll.setTextColor(UIUtils.getColor(R.color.c_383838));
        mTvPriceStoreGoodsAll.setTextColor(UIUtils.getColor(R.color.c_29CE7E));
        if (priceSore==0){
            priceSore=1;
            price="1";
        mIvPriceStoreGoodsAll.setImageResource(R.mipmap.direction_down);
        }else if (priceSore==1){
            priceSore=2;
            price="2";
        mIvPriceStoreGoodsAll.setImageResource(R.mipmap.direction_up);
        }else if (priceSore==2){
            priceSore=1;
            price="1";
            mIvPriceStoreGoodsAll.setImageResource(R.mipmap.direction_down);
        }
        recommend=null;
        currentPage=1;
        hotSell=null;

        onClickQuestIntent();

    }

    /**
     * 点击请求数据
     *
     */
    private void onClickQuestIntent() {

        Observable observable = ApiUtils.getApi().getStoreAllGoods(Contans.defaultToken, hotSell, recommend, price, mStoreId, 1, Contans.rows,BaseApplication.getNewUserId())
                .compose(RxHelper.getObservaleTransformer()).doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
                        if (mLoadingDialog == null) {

                            mLoadingDialog = LoadingDialogUtils.createLoadingDialog(mContext, "");
                        }
                        LoadingDialogUtils.show(mLoadingDialog);
                    }
                }).subscribeOn(AndroidSchedulers.mainThread());


        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<List<HotStoreGoods>>(mContext) {
            @Override
            protected void _onNext(StatusCode<List<HotStoreGoods>> listStatusCode) {
                LoadingDialogUtils.closeDialog(mLoadingDialog);

                List<HotStoreGoods> hotStoreGoods = listStatusCode.getData();

                if (hotStoreGoods!=null&& hotStoreGoods.size()>0){
                    mHotStoreGoods.clear();
                    mHotStoreGoods.addAll(hotStoreGoods);

                }else {
                    mHotStoreGoods.clear();
                    ToastUtils.makeText(listStatusCode.getDetailMsg());

                }
            mStoreHomeAdapter.notifyDataSetChanged();


            }

            @Override
            protected void _onError(String message) {

                LoadingDialogUtils.closeDialog(mLoadingDialog);
                mHotStoreGoods.clear();
                mStoreHomeAdapter.notifyDataSetChanged();


            }
        },"",lifecycleSubject,false,true);














    }


    public static Fragment getInstance(int storeId){

       StoreAllGoodsFragment storeAllGoodsFragment=new StoreAllGoodsFragment() ;
        Bundle bundle=new Bundle();
        bundle.putInt(Contans.INTENT_EXTRA,storeId);
        storeAllGoodsFragment.setArguments(bundle);
        return storeAllGoodsFragment;
    }
}
